#include "TextBox.h"

// Ctor
TextBox::TextBox(int x1, int  y1, int x2, int y2, int fps)
{
	m_x1 = x1;	m_y1 = y1;	m_x2 = x2;	m_y2 = y2;
	m_text[0] = '\0';
	m_textlen = 0;
	m_fps = fps;
}

// Append a character to the end of the text
void TextBox::Append(char c)
{
	if (c != 8 && m_textlen < 24 && c >= 46 && c <= 57 && c != 47) {
		m_text[m_textlen] = c;
		m_text[m_textlen + 1] = '\0';
		m_textlen++;
	}
	else if (c == 8) {
		if (m_textlen > 0)
		{
			m_textlen--;
			m_text[m_textlen] = '\0';
		}
	}
}

// Clear the text
void TextBox::Empty()
{
	m_textlen = 0;
	m_text[0] = '\0';
}

// Draw the text box
void TextBox::Draw()
{
	static int fps = 0;	// Set the blinking pointer

	//Set text style
	settextstyle(20, 0, "Verdana");

	// Draw the border
	setlinecolor(BLACK);
	setlinestyle(PS_SOLID | PS_JOIN_BEVEL, 5);
	rectangle(m_x1, m_y1, m_x2, m_y2);

	// Print the text
	outtextxy(m_x1 + 10, m_y1 + (m_y2 - m_y1 - 20) / 2, m_text);

	// Draw the Cursor
	fps++;
	if (fps < (m_fps))
	{
		setlinecolor(WHITE);
		int sx = m_x1 + 11 + textwidth(m_text);
		line(sx, m_y1 + (m_y2 - m_y1 - 20) / 2, sx, m_y1 + (m_y2 - m_y1 - 20) / 2 + 20);
	}
	else if (fps > (m_fps * 2))
		fps = 0;
}

// Get the input
char TextBox::Input() {
	char c = 0;
	if (_kbhit())
	{
		c = _getch();
	}
	return c;
}